package com.edu.service;


import com.edu.bean.AreaBean;
import com.edu.bean.CityBean;
import com.edu.bean.ProvinceBean;
import com.edu.dao.ProvinceDao;
import com.edu.utils.JedisPoolUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class ProvinceService {
    //缓存到的省编号
    private static ArrayList<Integer> pList = new ArrayList<>();
    //缓存到的市编号
    private static ArrayList<String> cList = new ArrayList<>();

    //获取省
    public static String getProvinces() throws JsonProcessingException {
        String provinceJson = null;
        Jedis jedis = JedisPoolUtils.getJedis();
        String province = jedis.get("province");
        if (province != null) {
            provinceJson = province;
        } else {
            List<ProvinceBean> provincesList = ProvinceDao.findProvinces();
            provinceJson = new ObjectMapper().writeValueAsString(provincesList);
            jedis.set("province", provinceJson);
        }
        return provinceJson;
    }

    //获取市
    public static String getCities(String provinceid) throws JsonProcessingException {
        String cityJson = null;
        Jedis jedis = JedisPoolUtils.getJedis();
        String city = jedis.get("city");

        if (city != null && pList.contains(Integer.parseInt(provinceid))) {
            cityJson = city;
        } else {
            //在这里给PList添加数据
            pList.add(Integer.parseInt(provinceid));

            List<CityBean> cityList = ProvinceDao.findCities(provinceid);
            cityJson = new ObjectMapper().writeValueAsString(cityList);
            jedis.set("city", cityJson);
        }
        return cityJson;
    }

    //获取区
    public static String getAreas(String cityid) throws JsonProcessingException {
        String areaJson = null;
        Jedis jedis = JedisPoolUtils.getJedis();
        String area = jedis.get("area");
        if (area != null && cList.contains(cityid)) {
            areaJson = area;
        } else {
            //在这里给cList添加数据
            cList.add(cityid);

            List<AreaBean> areaList = ProvinceDao.findAreas(cityid);
            areaJson = new ObjectMapper().writeValueAsString(areaList);
            jedis.set("area", areaJson);
        }
        return areaJson;
    }

}
